package main

import (
	"encoding/binary"
	"fmt"
	"golang.org/x/net/websocket"
	"io"
	"net/http"
	"packet"
	"server/pb"
)

func main() {
	println("服务器启动")

	wsServer := &WSServer{
		ListenAddr: "127.0.0.1:8889",
	}

	wsServer.start()
}

type WSServer struct {
	ListenAddr string
}

func (this *WSServer) start() {
	http.Handle("/websocket", websocket.Handler(this.handler))

	err := http.ListenAndServe(this.ListenAddr, nil)
	if err != nil {
		panic(fmt.Sprintf("服务器 ListenAndServe err:%s\n", err))
	}
}

func (this *WSServer) handler(conn *websocket.Conn) {
	defer conn.Close()

	fmt.Printf("\n\n客户端连接成功\n\n")

	for {
		headData := make([]byte, 2)

		_, err := io.ReadFull(conn, headData)
		if err != nil {
			if err != io.EOF {
				fmt.Printf("\n客户端 head ReadFull err:%s\n", err)
			}
			return
		}

		bodyLen := binary.BigEndian.Uint16(headData)
		bodyData := make([]byte, bodyLen)

		_, err = io.ReadFull(conn, bodyData)
		if err != nil {
			fmt.Printf("\n客户端 body ReadFull err:%s\n", err)
			return
		}

		dispatch(conn, bodyData)
	}
}

func dispatch(conn *websocket.Conn, bodyData []byte) {
	packetIdData := bodyData[:2]
	packetId := binary.BigEndian.Uint16(packetIdData)
	println("协议 ID:", packetId)

	packetData := bodyData[2:]
	packetInst := packet.NewReadBuff(packetData)

	switch packetId {
	case pb.PRoleLogin:
		roleLogin := pb.RoleLoginDecode(packetInst)
		fmt.Printf("请求登录:%v\n", roleLogin)

		goodsItems := []*pb.GoodsItem{{Id: 100, Num: 11}, {Id: 200, Num: 22}}
		roleLoginOk := pb.RoleLoginOk{Uid: 10086, Uname: "golang", GoodsItems: goodsItems, Video: roleLogin.Video}

		goodsItem := pb.GoodsItem{Id: 300, Num: 33}

		websocket.Message.Send(conn, append(roleLoginOk.Encode(), goodsItem.Encode()...))
	default:
		fmt.Println("未知协议 ID:", packetId)
	}
}
